package com.example.mylibrary.utils

import android.animation.Animator
import android.animation.AnimatorInflater
import android.annotation.SuppressLint
import android.app.Activity
import android.app.Application
import android.content.Context
import android.content.res.Resources
import android.graphics.Point
import android.graphics.drawable.Drawable
import android.os.Build
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import android.widget.TextView
import android.widget.Toast
import androidx.annotation.StringRes
import java.math.RoundingMode
import java.text.DecimalFormat
import java.text.SimpleDateFormat
import java.util.*

@SuppressLint("ShowToast")
object UiTools {

    private var toast: Toast? = null

    private var decimalFormat: DecimalFormat = DecimalFormat()

    private val simpleDateFormat: SimpleDateFormat =
        SimpleDateFormat("yyyy.MM.dd HH:mm:ss", Locale.CHINA)

    lateinit var resources: Resources

    lateinit var context: Context

    private val stringBuffer = StringBuffer()

    fun initUiTools(application: Application) {
        resources = application.resources
        context = application.applicationContext
    }

    /**
     * 获取屏幕宽
     *
     * @param activity 当前页面的activity
     * @return 当前页面宽
     */
    fun getDeviceWidth(activity: Activity): Int {
        val display = activity.windowManager.defaultDisplay
        val p = Point()
        display.getSize(p)
        return p.x
    }

    /**
     * 获取屏幕的高
     *
     * @param activity 当前页面的activity
     * @return 当前页面高
     */
    fun getDeviceHeight(activity: Activity): Int {
        val display = activity.windowManager.defaultDisplay
        val p = Point()
        display.getSize(p)
        return p.y
    }

    /**
     * 判断传入的字符串是否为空
     *
     * @param strings 传入的字符串数组
     * @return 全部非空返回true 否则返回false
     */
    fun noEmpty(vararg strings: String?): Boolean {
        if (strings.isNotEmpty()) {
            for (string in strings) {
                if (TextUtils.isEmpty(string)) {
                    return false
                }
            }
            return true
        }
        return false
    }

    /**
     * 要获取内容的TextView
     *
     * @param textView TextView
     * @return TextView内容
     */
    fun getText(textView: TextView): String {
        return textView.text.toString().trim()
    }

    /**
     * 要获取内容的TextView
     *
     * @param textView TextView
     * @return TextView内容
     */
    fun getHint(textView: TextView): String? {
        return textView.hint.toString().trim()
    }

    /**
     * 格式化数字为指定格式
     *
     * @param number  需要格式化的数字
     * @param pattern 指定格式
     * @return 格式化完成后的字符串
     */
    fun formatNumber(number: Any?, pattern: String?): String? {
        return try {
            decimalFormat = DecimalFormat()
            decimalFormat.applyPattern(pattern)
            if (number is Double) {
                decimalFormat.format(number)
            } else if (number is Long) {
                decimalFormat.format(number)
            } else if (number is String) {
                if (noEmpty(number as String?)) {
                    val replace =
                        if (number.contains(",")) number.replace(",", "") else (number as String?)!!
                    return if (number.contains(".")) {
                        val aDouble = java.lang.Double.valueOf(replace)
                        formatNumber(aDouble, pattern)
                    } else {
                        val aLong = java.lang.Long.valueOf(replace)
                        formatNumber(aLong, pattern)
                    }
                }
                "0"
            } else {
                decimalFormat.format(number)
            }
        } catch (e: Exception) {
            "0"
        }
    }

    fun formatNumber(number: Any?, pattern: String?, roundingMode: RoundingMode?): String? {
        return try {
            decimalFormat = DecimalFormat()
            decimalFormat.applyPattern(pattern)
            decimalFormat.setRoundingMode(roundingMode)
            if (number is Double) {
                decimalFormat.format(number)
            } else if (number is Long) {
                decimalFormat.format(number)
            } else if (number is String) {
                if (noEmpty(number as String?)) {
                    val replace =
                        if (number.contains(",")) number.replace(",", "") else (number as String?)!!
                    return if (number.contains(".")) {
                        val aDouble = java.lang.Double.valueOf(replace)
                        formatNumber(aDouble, pattern)
                    } else {
                        val aLong = java.lang.Long.valueOf(replace)
                        formatNumber(aLong, pattern)
                    }
                }
                "0"
            } else {
                decimalFormat.format(number)
            }
        } catch (e: Exception) {
            "0"
        }
    }

    /**
     * 格式化数字为指定格式
     *
     * @param number  需要格式化的数字
     * @param pattern 指定格式
     * @return 格式化完成后的字符串
     */
    fun formatDecimal(number: Any?, pattern: Int, roundingMode: RoundingMode?): String? {
        return try {
            decimalFormat = DecimalFormat()
            decimalFormat.setGroupingUsed(false)
            decimalFormat.applyPattern("")
            decimalFormat.setRoundingMode(roundingMode)
            decimalFormat.setMaximumFractionDigits(pattern)
            if (number is Double) {
                decimalFormat.format(number)
            } else if (number is Long) {
                decimalFormat.format(number)
            } else if (number is String) {
                if (noEmpty(number as String?)) {
                    val replace =
                        if (number.contains(",")) number.replace(",", "") else (number as String?)!!
                    return if (number.contains(".")) {
                        val aDouble = java.lang.Double.valueOf(replace)
                        formatDecimal(aDouble, pattern, roundingMode)
                    } else {
                        val aLong = java.lang.Long.valueOf(replace)
                        formatDecimal(aLong, pattern, roundingMode)
                    }
                }
                "0"
            } else {
                decimalFormat.format(number)
            }
        } catch (e: Exception) {
            e.printStackTrace()
            "0"
        }
    }

    fun formatDecimal(number: Any?, pattern: Int): String? {
        return try {
            decimalFormat = DecimalFormat()
            decimalFormat.setGroupingUsed(false)
            decimalFormat.setMaximumFractionDigits(pattern)
            stringBuffer.setLength(0)
            if (pattern > 0) {
                stringBuffer.append("0.")
                for (i in 0 until pattern) {
                    stringBuffer.append("0")
                }
            } else {
                stringBuffer.append("0")
            }
            decimalFormat.applyPattern(stringBuffer.toString())
            if (number is Double) {
                decimalFormat.format(number)
            } else if (number is Long) {
                decimalFormat.format(number)
            } else if (number is String) {
                if (noEmpty(number as String?)) {
                    val replace =
                        if (number.contains(",")) number.replace(",", "") else (number as String?)!!
                    return if (number.contains(".")) {
                        val aDouble = java.lang.Double.valueOf(replace)
                        formatDecimal(aDouble, pattern)
                    } else {
                        val aLong = java.lang.Long.valueOf(replace)
                        formatDecimal(aLong, pattern)
                    }
                }
                "0"
            } else {
                decimalFormat.format(number)
            }
        } catch (e: Exception) {
            e.printStackTrace()
            "0"
        }
    }

    fun showToast(text: String?) {
        if (toast == null) {
            toast = Toast.makeText(context, "", Toast.LENGTH_SHORT)
        }
        toast?.setText(text)
        toast?.show()
    }

    fun showToast(@StringRes stringRes: Int) {
        if (toast == null) {
            toast = Toast.makeText(context, "", Toast.LENGTH_SHORT)
        }
        toast?.setText(stringRes)
        toast?.show()
    }

    fun showToastLong(text: String?) {
        if (toast == null) {
            toast = Toast.makeText(context, "", Toast.LENGTH_LONG)
        }
        toast?.setText(text)
        toast?.show()
    }

    fun showToastLong(@StringRes stringRes: Int) {
        if (toast == null) {
            toast = Toast.makeText(context, "", Toast.LENGTH_LONG)
        }
        toast?.setText(stringRes)
        toast?.show()
    }

    /**
     * 获取资源id对应的字符串
     *
     * @param resId 资源ID
     * @return 返回对应字符串
     */
    fun getString(resId: Int): String {
        return resources.getString(resId)
    }

    /**
     * 获取资源id对应的字符串数组
     *
     * @param resId 资源ID
     * @return 返回对应字符串数组
     */
    fun getStringArray(resId: Int): Array<String> {
        return resources.getStringArray(resId)
    }

    fun getIntArray(resId: Int): IntArray? {
        return resources.getIntArray(resId)
    }

    /**
     * 获取资源id对应的Drawable对象
     *
     * @param resId 资源ID
     * @return 返回Drawable对象
     */
    fun getDrawable(resId: Int): Drawable? {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            resources.getDrawable(resId, null)
        } else {
            resources.getDrawable(resId)
        }
    }

    fun getDimen(resId: Int): Float? {
        return resources.getDimension(resId)
    }

    /**
     * 获取资源id对应的颜色值
     *
     * @param resId 资源ID
     * @return 返回对应颜色值
     */
    fun getColor(resId: Int): Int {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) resources.getColor(
            resId,
            null
        ) else resources.getColor(resId)
    }

    fun getAnimation(resId: Int): Animation? {
        return AnimationUtils.loadAnimation(context, resId)
    }

    fun getAnimator(resId: Int): Animator? {
        return AnimatorInflater.loadAnimator(context, resId)
    }

    /**
     * 根据手机的分辨率从 dip 的单位 转成为 px(像素)
     *
     * @param dip 需要转换的dp值
     * @return 返回转换后的值
     */
    fun dip2px(dip: Float): Int {
        val scale: Float = resources.displayMetrics.density
        return (dip * scale + 0.5f).toInt()
    }


    /**
     * 根据手机的分辨率从 dip 的单位 转成为 px(像素)
     *
     * @param px 需要转换的dp值
     * @return 返回转换后的值
     */
    fun px2dip(px: Int): Int {
        val scale: Float = resources.displayMetrics.density
        return (px / scale + 0.5f).toInt()
    }

    /**
     * 解析xml资源到view
     */
    fun parseLayout(resLayout: Int, root: ViewGroup?): View? {
        val from = LayoutInflater.from(context)
        return from.inflate(resLayout, root, false)
    }

    /**
     * 解析xml资源到view
     */
    fun parseLayout(resLayout: Int): View? {
        return View.inflate(context, resLayout, null)
    }

    /**
     * 将数字转化为#格式, 用于格式化数字的规则
     */
    fun getPattern(formatValue: Double): String? {
        val stringValue = formatValue.toString()
        return stringValue.replace("[^.?]".toRegex(), "#")
    }

    /**
     * 将数字字符转化为#格式, 用于格式化数字的规则
     */
    fun getPattern(formatValue: String): String? {
        return formatValue.replace("[^.?]".toRegex(), "#")
    }

    /**
     * 格式化毫秒值为  yyyy.MM.dd HH:mm:ss
     */
    fun formatLongTime(milliSecond: Long): String? {
        return simpleDateFormat.format(Date(milliSecond))
    }

    /**
     * 格式化毫秒值为 pattern 的格式类型
     */
    fun formatLongTime(milliSecond: Long, pattern: String?): String? {
        simpleDateFormat.applyPattern(pattern)
        return simpleDateFormat.format(Date(milliSecond))
    }

    /**
     * 格式化日期为 yyyy.MM.dd HH:mm:ss
     */
    fun formatDate(date: Date): String? {
        return simpleDateFormat.format(date)
    }

    /**
     * 格式化日期为 pattern 的格式类型
     */
    fun formatDate(date: Date, pattern: String?): String? {
        simpleDateFormat.applyPattern(pattern)
        return simpleDateFormat.format(date)
    }

    /**
     * 将时间毫秒转换为 -天-时-分-秒 格式
     */
    fun getTime(millisecond: Long): String? {
        var second = millisecond
        val days = second / 86400 //转换天数
        second %= 86400 //剩余秒数
        val hours = second / 3600 //转换小时数
        val hour: String
        hour = if (hours > 10) {
            hours.toString() + ""
        } else {
            "0$hours"
        }
        second %= 3600 //剩余秒数
        val minute: String
        val minutes = second / 60 //转换分钟
        minute = if (minutes > 10) {
            minutes.toString() + ""
        } else {
            "0$minutes"
        }
        second %= 60 //剩余秒数
        val seconds: String
        seconds = if (second > 10) {
            second.toString() + ""
        } else {
            "0$second"
        }
        return if (days > 0) {
            days.toString() + "天 " + hour + ":" + minute + ":" + seconds
        } else {
            "$hour:$minute:$seconds"
        }
    }

    /**
     * 检测String是否全是中文
     *
     * @param name
     * @return
     */
    fun checkNameChinese(name: String): Boolean {
        var res = true
        for (element in name) {
            if (!isChinese(element)) {
                res = false
                break
            }
        }
        return res
    }

    /**
     * 判定输入汉字
     *
     * @param c
     * @return
     */
    private fun isChinese(c: Char): Boolean {
        val ub = Character.UnicodeBlock.of(c)
        return ub === Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
                || ub === Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
                || ub === Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
                || ub === Character.UnicodeBlock.GENERAL_PUNCTUATION
                || ub === Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
                || ub === Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS
    }

}